package com.zw.shardedJedis.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import redis.clients.jedis.JedisPoolConfig;

import java.util.List;

/**
 * Created by zwz
 * date 2017/4/19
 * project com.zw.shardedJedis.config
 */
@Configuration
public class PoolConfig {

    private static final Logger log = LoggerFactory.getLogger(PoolConfig.class);

    @Value("#{'${myRedis.sentinel.urls:}'.split(';')}")
    private List<String> urls;
    @Value("#{'${myRedis.sentinel.masterNames:}'.split(',')}")
    private List<String> masterNames;

    @Value("${myRedis.sentinel.soTimeout}")
    private int soTimeout;
    @Value("${myRedis.sentinel.retrySentinel}")
    private	int retrySentinel;
    @Value("${myRedis.sentinel.connectionTimeout}")
    private	int connectionTimeout;
    @Value("#{'${myRedis.sentinel.password:}'.equals('')?null:'${myRedis.sentinel.password:}'}")
    private	String password;
    @Value("${myRedis.sentinel.database}")
    private	int database;
    @Value("${myRedis.sentinel.slaveTime}")
    private	Long slaveTime;
    
    
    @Bean
    @ConfigurationProperties(prefix = "myRedis.JedisPoolConfig")
    public JedisPoolConfig jedisPoolConfig() {
        return new JedisPoolConfig();
    }

    @Bean
    public ShardedJedisSentinelPool shardedJedisSentinelPool(JedisPoolConfig jedisPoolConfig) throws Exception {
        if (StringUtils.isEmpty(this.urls)||StringUtils.isEmpty(this.masterNames)) {
            throw new Exception("redis PoolConfig: init error,Sentinel url or masterNames is null.");
        } else {
            if (!CollectionUtils.isEmpty(urls) && !CollectionUtils.isEmpty(masterNames)) {
                    ShardedJedisSentinelPool pool;
                    try {
                        pool = new ShardedJedisSentinelPool(masterNames, urls,jedisPoolConfig,soTimeout,retrySentinel,
                                connectionTimeout,password,database,slaveTime);
                        return pool;
                    } catch (Exception e) {
                        log.error("ShardedJedisSentinelPool Instantiation error");
                        log.error(e.getMessage());
                        throw e;
                    }
            } else {
                throw new Exception("redis PoolConfig: init error,Please check Sentinel url or masterNames configuration.");
            }
        }
    }

}
